<template>
    <div class="file-edit-container">
  <!-- 头部区域 -->
  <el-page-header @back="goBack" :icon="ArrowLeft" class="header">
    <template #content>
      <span class="text-large font-900 mr-3"> 编辑文件 </span>
    </template>
  </el-page-header>

  <el-collapse v-model="activeNames" @change="handleChange" class="file-edit-collapse">
      <el-collapse-item title="原文内容" name="1">
        <div class="text-content-wrapper">
          <div 
            class="text-content" 
            :class="{ 'text-collapsed': !isExpanded && needsExpand }"
            ref="textContentRef"
            v-html="sourceText || '（暂无原文内容）'"
          >
          </div>
          <div v-if="needsExpand" class="expand-button-wrapper">
            <el-button 
              link 
              @click="toggleExpand"
              class="expand-button"
            >
              <el-icon :class="{ 'rotate-icon': isExpanded }">
                <ArrowDown />
              </el-icon>
              {{ isExpanded ? '收起' : '展开' }}
            </el-button>
          </div>
        </div>
      </el-collapse-item>
      <el-collapse-item title="AI纪要" name="2">
        <template #icon="{ isActive }">
          <div class="flex items-center" v-if="isActive" @click.stop>
          <el-button type="primary" class="ml-2" @click="saveFileData">保存修改</el-button>
        </div>
        </template>
        <!-- WangEditor 富文本编辑器 -->
        <div class="editor-wrapper">
          <Toolbar
            class="editor-toolbar"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            :mode="mode"
          />
          <Editor
            class="rich-editor"
            v-model="editorContent"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="handleCreated"
            @onChange="handleChange"
          />
        </div>
      </el-collapse-item>
    </el-collapse>

</div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, shallowRef, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import { ArrowLeft, ArrowDown } from "@element-plus/icons-vue";
import { getFileDetail, getRecordDetail, saveFile} from "@/api/file";
import { ElMessage } from "element-plus";
// @ts-ignore
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import type { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor';
import '@wangeditor/editor/dist/css/style.css';

const router = useRouter();
const goBack = () => {
  router.back();
};
const id = ref(router.currentRoute.value.query.id);
const type = ref(router.currentRoute.value.query.type);

const activeNames = ref(["1", "2"]); // 默认展开所有折叠面板

const sourceText = ref('');
const textContentRef = ref<HTMLElement | null>(null);
const isExpanded = ref(false);
const needsExpand = ref(false);

// 检查文本是否超过10行
const checkTextHeight = () => {
  nextTick(() => {
    if (textContentRef.value) {
      const lineHeight = parseFloat(getComputedStyle(textContentRef.value).lineHeight);
      const maxHeight = lineHeight * 10;
      const actualHeight = textContentRef.value.scrollHeight;
      needsExpand.value = actualHeight > maxHeight;
      
      console.log('检查文本高度:', {
        lineHeight,
        maxHeight,
        actualHeight,
        needsExpand: needsExpand.value
      });
    }
  });
};

const toggleExpand = () => {
  isExpanded.value = !isExpanded.value;
  console.log('切换展开状态:', isExpanded.value ? '展开' : '收起');
};

const getFileDetailData = async () => {
  if(type.value == '0') {
  const res = await getFileDetail({ id: id.value });
  if (res.code === 1) {
    // 设置所有数据
    sourceText.value = res.data.content;
    editorContent.value = res.data.fileText;
    // 等待 DOM 更新后检查文本高度
    checkTextHeight();
  }
  } else {
    const res = await getRecordDetail({ templateType:0, id: id.value });
    if (res.code === 1) {
      sourceText.value = res.data.content;
      editorContent.value = res.data.minutes;
      // 等待 DOM 更新后检查文本高度
      checkTextHeight();
    }
  }
};

onMounted(() => {
  getFileDetailData();
});

// WangEditor 相关配置
const editorRef = shallowRef<IDomEditor>();
const editorContent = ref('<p>请在此编辑AI纪要...</p>');
const mode = ref('default'); // 或 'simple'

// 工具栏配置 - 适合移动端的精简配置
const toolbarConfig: Partial<IToolbarConfig> = {
  toolbarKeys: [
    'headerSelect', // 标题选择
    '|',
    'bold', // 粗体
    'italic', // 斜体
    'underline', // 下划线
    '|',
    'bulletedList', // 无序列表
    'numberedList', // 有序列表
    '|',
    'color', // 文字颜色
    'bgColor', // 背景色
    '|',
    'undo', // 撤销
    'redo', // 重做
    '|',
    'clearStyle', // 清除格式
  ],
};

// 编辑器配置
const editorConfig: Partial<IEditorConfig> = {
  placeholder: '请在此编辑AI纪要内容...',
  MENU_CONF: {
    // 配置颜色
    color: {
      colors: ['#000000', '#333333', '#666666', '#999999', '#E53333', '#E56600', '#FF9900', '#64BD63', '#3D8ED7', '#9D50BB']
    },
    bgColor: {
      colors: ['#FFFFFF', '#F5F7FA', '#FFF5E6', '#FFE6E6', '#E6F7FF', '#F0F5FF']
    }
  }
};

// 编辑器创建完成
const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor;
  console.log('WangEditor created:', editor);
};

// 编辑器内容变化
const handleChange = (editor: IDomEditor) => {
  console.log('Editor content changed:', editor.getHtml());
};

// 保存编辑文件
const saveFileData = async () => {
  const res = await saveFile({ id: id.value, minutes: editorContent.value });
  if (res.code === 1) {
    ElMessage.success('保存成功');
  }
};
// 组件销毁前，销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

</script>

<style lang="scss" scoped>
.file-edit-container {
  height: 100vh;
  padding: 20px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}
.header {
  flex-shrink: 0;
  :deep(.el-page-header__content) {
    font-size: 16px;
    font-weight: 600;
  }
}
.file-edit-collapse {
  width:100%;
  margin-top: 20px;
  flex: 1;
  :deep(.el-collapse-item__header) {
    font-size: 16px;
    font-weight: 600;
  }
  :deep(.el-collapse-item__content) {
    font-size: 14px;
    color: #606266;
  }
}

.text-content-wrapper {
  position: relative;
  background-color: #fff;
}

.text-content {
  line-height: 1.8;
  white-space: pre-wrap;
  word-break: break-word;
  transition: all 0.3s ease;
  overflow: hidden;
  
  &.text-collapsed {
    max-height: calc(1.8em * 10); /* 10行的高度 */
    position: relative;
    
    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: calc(1.8em * 3); /* 最后3行渐隐 */
      background: linear-gradient(to bottom, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1));
      pointer-events: none;
      z-index: 1;
    }
  }
  
  &:not(.text-collapsed) {
    max-height: none;
  }
}

.expand-button-wrapper {
  text-align: center;
  margin-top: 10px;
  
  .expand-button {
    font-size: 14px;
    color: #409eff;
    
    .el-icon {
      transition: transform 0.3s ease;
      
      &.rotate-icon {
        transform: rotate(180deg);
      }
    }
  }
}

// WangEditor 编辑器样式
.editor-wrapper {
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: hidden;
  
  .editor-toolbar {
    border-bottom: 1px solid #e8e8e8;
    background-color: #f5f7fa;
    
    // 移动端优化工具栏
    @media (max-width: 768px) {
      :deep(.w-e-toolbar) {
        flex-wrap: wrap;
        padding: 8px 4px;
      }
      
      :deep(.w-e-bar-item) {
        padding: 4px 6px !important;
        font-size: 13px !important;
        
        button {
          padding: 4px 6px !important;
          
          svg {
            width: 14px !important;
            height: 14px !important;
          }
        }
      }
      
      :deep(.w-e-select-list) {
        font-size: 13px !important;
      }
      
      :deep(.w-e-drop-panel) {
        font-size: 13px !important;
      }
    }
  }
  
  .rich-editor {
    height: 600px !important;
    overflow-y: auto;
    
    // 移动端高度调整
    @media (max-width: 768px) {
      height: 300px !important;
    }
    
    // 编辑器内容区域样式
    :deep(.w-e-text-container) {
      background-color: #fff;
      
      [data-slate-editor] {
        padding: 16px;
        font-size: 14px;
        line-height: 1.6;
        
        
        @media (max-width: 768px) {
          padding: 12px;
          font-size: 13px;
        }
        
        p {
          margin: 8px 0;
        }
        
        h1, h2, h3 {
          font-weight: 600;
          margin: 16px 0 8px;
          color: #303133;
        }
        
        h1 {
          font-size: 24px;
          @media (max-width: 768px) {
            font-size: 20px;
          }
        }
        
        h2 {
          font-size: 20px;
          @media (max-width: 768px) {
            font-size: 18px;
          }
        }
        
        h3 {
          font-size: 18px;
          @media (max-width: 768px) {
            font-size: 16px;
          }
        }
        
        ul, ol {
          margin: 8px 0;
          padding-left: 24px;
        }
        
        li {
          margin: 4px 0;
        }
        
        blockquote {
          border-left: 3px solid #409eff;
          padding-left: 12px;
          margin: 12px 0;
          color: #666;
        }
        
        code {
          background-color: #f5f7fa;
          padding: 2px 6px;
          border-radius: 3px;
          font-family: 'Courier New', monospace;
          font-size: 0.9em;
        }
        
        pre {
          background-color: #f5f7fa;
          padding: 12px;
          border-radius: 4px;
          overflow-x: auto;
          
          code {
            background: none;
            padding: 0;
          }
        }
      }
    }
    
    // 占位符样式
    :deep(.w-e-text-placeholder) {
      color: #c0c4cc;
      font-style: normal;
    }
  }
}
</style>
